package snowflake

import (
	"errors"
	"github.com/bwmarrin/snowflake"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"time"
)

var (
	serialNodeBase  *snowflake.Node //基础的流水节点1
	serialNodeBase2 *snowflake.Node //基础的流水节点2
)

func InitSerialNumberNode() {
	ctx := gctx.GetInitCtx()
	config, _ := g.Cfg().Get(ctx, "system.machineId")
	machineID := config.Int64()
	dataCenters := map[string]int64{
		"SerialNodeBase":  1, //普通节点1
		"serialNodeBase2": 2, //普通节点2
	}
	for nodeName, dataCenter := range dataCenters {
		node, err := newSnowFlake(machineID, dataCenter)
		if err != nil {
			g.Log().Error(ctx, err.Error())
		}
		switch nodeName {
		case "SerialNodeBase":
			serialNodeBase = node
		case "TransferCommandNode":
			serialNodeBase2 = node
		}
	}
}

// newSnowFlake 初始化一个雪花算法节点
func newSnowFlake(machineId int64, dataCenter int64) (snowFlakeNode *snowflake.Node, err error) {
	// 设置雪花算法起始的时间
	snowFlakeStartTime := "2024-06-01"

	var ts time.Time
	ts, err = time.Parse(time.DateOnly, snowFlakeStartTime)
	if err != nil {
		return
	}
	if machineId < 0 || machineId > 9 {
		err = errors.New("InitSnowFlake fail, machineId must in [0-9]")
		return
	}
	if dataCenter < 0 || dataCenter > 99 {
		err = errors.New("InitSnowFlake fail, dataCenter must in [0-9]")
		return
	}
	//Node number must be between 0 and 1023：按机器+数据中心组合拼装node值，实现同一机器上拥有不同的node节点
	node := machineId*100 + dataCenter

	snowflake.Epoch = ts.UnixNano() / 1e6
	snowFlakeNode, err = snowflake.NewNode(node)
	if err != nil {
		return
	}
	return
}

func GenerateSerialNo() string {
	return serialNodeBase.Generate().String()
}

func GenerateSerialNo2() string {
	return serialNodeBase2.Generate().String()
}
